<template>
  <div class="hash-operations">
    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span><el-icon><Edit /></el-icon> 设置哈希字段</span>
        </div>
      </template>
      <el-form :model="hsetForm" label-width="120px" label-position="left">
        <el-form-item label="键名">
          <el-input v-model="hsetForm.key" placeholder="请输入键名" clearable />
        </el-form-item>
        <el-form-item label="字段名">
          <el-input v-model="hsetForm.field" placeholder="请输入字段名" clearable />
        </el-form-item>
        <el-form-item label="值">
          <el-input v-model="hsetForm.value" placeholder="请输入值" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleHSet" :icon="Check">设置</el-button>
          <el-button @click="resetHSetForm" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span><el-icon><Search /></el-icon> 获取哈希字段</span>
        </div>
      </template>
      <el-form :model="hgetForm" label-width="120px" label-position="left">
        <el-form-item label="键名">
          <el-input v-model="hgetForm.key" placeholder="请输入键名" clearable />
        </el-form-item>
        <el-form-item label="字段名">
          <el-input v-model="hgetForm.field" placeholder="请输入字段名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleHGet" :icon="Search">获取</el-button>
          <el-button @click="resetHGetForm" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
      <div v-if="hgetResult !== null" class="result-box">
        <div class="result-header">
          <h4>哈希字段值:</h4>
          <el-button type="text" @click="copyHGetResult" :icon="CopyDocument">复制</el-button>
        </div>
        <el-alert
          v-if="hgetResult === null"
          title="未找到该字段"
          type="warning"
          :closable="false"
          show-icon
        />
        <div v-else class="hash-display">
          <div class="hash-header">
            <span class="hash-title">响应信息:</span>
            <div class="hash-actions">
              <el-button 
                type="text" 
                size="small" 
                @click="copyHGetResult"
                :icon="CopyDocument"
              >
                复制所有数据
              </el-button>
            </div>
          </div>
          <div class="hash-content">
            <div class="hash-item">
               <div class="hash-field">
                 <el-tag type="success" size="small">success</el-tag>
               </div>
               <div class="hash-separator">:</div>
               <div class="hash-value">
                 <span class="value-text">{{ hgetResult.success }}</span>
                 <el-button 
                   type="text" 
                   size="small" 
                   @click="copyFieldValue(hgetResult.success)"
                   :icon="CopyDocument"
                   class="copy-btn"
                 >
                   复制
                 </el-button>
               </div>
             </div>
             <div class="hash-item">
               <div class="hash-field">
                 <el-tag type="primary" size="small">key</el-tag>
               </div>
               <div class="hash-separator">:</div>
               <div class="hash-value">
                 <span class="value-text">{{ hgetResult.key }}</span>
                 <el-button 
                   type="text" 
                   size="small" 
                   @click="copyFieldValue(hgetResult.key)"
                   :icon="CopyDocument"
                   class="copy-btn"
                 >
                   复制
                 </el-button>
               </div>
             </div>
             <div class="hash-item">
               <div class="hash-field">
                 <el-tag type="info" size="small">field</el-tag>
               </div>
               <div class="hash-separator">:</div>
               <div class="hash-value">
                 <span class="value-text">{{ hgetResult.field }}</span>
                 <el-button 
                   type="text" 
                   size="small" 
                   @click="copyFieldValue(hgetResult.field)"
                   :icon="CopyDocument"
                   class="copy-btn"
                 >
                   复制
                 </el-button>
               </div>
             </div>
            <div class="hash-item">
               <div class="hash-field">
                 <el-tag type="warning" size="small">data</el-tag>
               </div>
               <div class="hash-separator">:</div>
               <div class="hash-value">
                   <span class="value-text">{{ hgetResult.data }}</span>
                   <el-button 
                     type="text" 
                     size="small" 
                     @click="copyFieldValue(hgetResult.data)"
                     :icon="CopyDocument"
                     class="copy-btn"
                   >
                     复制
                   </el-button>
                 </div>
             </div>
            <div class="hash-item">
              <div class="hash-field">
                <el-tag type="info" size="small">message</el-tag>
              </div>
              <div class="hash-separator">:</div>
              <div class="hash-value">
                <span class="value-text">{{ hgetResult.message }}</span>
                <el-button 
                  type="text" 
                  size="small" 
                  @click="copyFieldValue(hgetResult.message)"
                  :icon="CopyDocument"
                  class="copy-btn"
                >
                  复制
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span><el-icon><Document /></el-icon> 获取所有哈希字段及其值</span>
        </div>
      </template>
      <el-form :model="hgetallForm" label-width="120px" label-position="left">
        <el-form-item label="键名">
          <el-input v-model="hgetallForm.key" placeholder="请输入键名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleHGetAll" :icon="Search">获取所有字段及值</el-button>
          <el-button @click="resetHGetAllForm" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
      <div v-if="Object.keys(hgetallResult).length > 0 || hgetallResultEmpty" class="result-box">
        <div class="result-header">
          <h4>哈希字段及值 ({{ Object.keys(hgetallResult).length }} 个字段):</h4>
          <el-button type="text" @click="copyHGetAllResult" :icon="CopyDocument">复制</el-button>
        </div>
        <el-alert
          v-if="Object.keys(hgetallResult).length === 0 && hgetallResultEmpty"
          title="未找到该键或哈希为空"
          type="warning"
          :closable="false"
          show-icon
        />
        <div v-else class="hash-display">
          <div class="hash-header">
            <span class="hash-title">哈希字段及值:</span>
            <div class="hash-actions">
              <el-button 
                type="text" 
                size="small" 
                @click="copyHGetAllResult"
                :icon="CopyDocument"
              >
                复制所有数据
              </el-button>
            </div>
          </div>
          <div class="hash-content">
            <div 
              v-for="(value, field) in hgetallResult" 
              :key="field"
              class="hash-item"
            >
              <div class="hash-field">
                <el-tag type="info" size="small">{{ field }}</el-tag>
              </div>
              <div class="hash-separator">:</div>
              <div class="hash-value">
                <span class="value-text">{{ value }}</span>
                <el-button 
                  type="text" 
                  size="small" 
                  @click="copyFieldValue(value)"
                  :icon="CopyDocument"
                  class="copy-btn"
                >
                  复制
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span><el-icon><Delete /></el-icon> 删除哈希字段</span>
        </div>
      </template>
      <el-form :model="hdelForm" label-width="120px" label-position="left">
        <el-form-item label="键名">
          <el-input v-model="hdelForm.key" placeholder="请输入键名" clearable />
        </el-form-item>
        <el-form-item label="字段名">
          <el-input v-model="hdelForm.field" placeholder="请输入字段名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="handleHDel" :icon="Delete">删除</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Check, Search, Refresh, Delete, Document, CopyDocument } from '@element-plus/icons-vue'
import { hSet, hGet, hGetAll, hDel } from '../api/redis'

const hsetForm = reactive({
  key: '',
  field: '',
  value: ''
})

const hgetForm = reactive({
  key: '',
  field: ''
})

const hgetallForm = reactive({
  key: ''
})

const hdelForm = reactive({
  key: '',
  field: ''
})

const hgetResult = ref<any>(null)
const hgetallResult = ref<Record<string, string>>({})
const hgetallResultEmpty = ref(false)

// 将哈希结果转换为表格数据
// 复制单个字段值的功能
const copyFieldValue = (value: string) => {
  if (value) {
    navigator.clipboard.writeText(value)
    ElMessage.success('字段值已复制到剪贴板')
  }
}

const handleHSet = async () => {
  if (!hsetForm.key || !hsetForm.field) {
    ElMessage.warning('请输入键名和字段名')
    return
  }
  
  try {
    await hSet(hsetForm.key, hsetForm.field, hsetForm.value)
    ElMessage.success('设置成功')
    resetHSetForm()
  } catch (error) {
    ElMessage.error('设置失败')
  }
}

const handleHGet = async () => {
  if (!hgetForm.key || !hgetForm.field) {
    ElMessage.warning('请输入键名和字段名')
    return
  }
  
  try {
    const response = await hGet(hgetForm.key, hgetForm.field)
    hgetResult.value = response.data
    if (hgetResult.value === null) {
      ElMessage.warning('未找到该字段')
    } else {
      ElMessage.success('获取成功')
    }
  } catch (error) {
    ElMessage.error('获取失败')
    hgetResult.value = null
  }
}

const handleHGetAll = async () => {
  if (!hgetallForm.key) {
    ElMessage.warning('请输入键名')
    return
  }
  
  try {
    const response = await hGetAll(hgetallForm.key)
    hgetallResult.value = response.data || {}
    hgetallResultEmpty.value = true
    
    const fieldCount = Object.keys(hgetallResult.value).length
    if (fieldCount === 0) {
      ElMessage.warning('未找到该键或哈希为空')
    } else {
      ElMessage.success(`获取成功，共 ${fieldCount} 个字段`)
    }
  } catch (error) {
    ElMessage.error('获取失败')
    hgetallResult.value = {}
    hgetallResultEmpty.value = false
  }
}

const copyHGetAllResult = () => {
  if (Object.keys(hgetallResult.value).length > 0) {
    navigator.clipboard.writeText(JSON.stringify(hgetallResult.value, null, 2))
    ElMessage.success('所有字段及值已复制到剪贴板')
  }
}

const handleHDel = async () => {
  if (!hdelForm.key || !hdelForm.field) {
    ElMessage.warning('请输入键名和字段名')
    return
  }
  
  try {
    const response = await hDel(hdelForm.key, hdelForm.field)
    const result = response.data
    
    if (result.success) {
      ElMessage.success(result.message || '删除成功')
      
      // 保存当前要删除的键和字段
      const deletedKey = hdelForm.key
      const deletedField = hdelForm.field
      
      // 清空表单
      hdelForm.key = ''
      hdelForm.field = ''
      
      // 如果当前正在查询的键和字段被删除，清空结果
      if (hgetForm.key === deletedKey && hgetForm.field === deletedField) {
        hgetResult.value = null
      }
      if (hgetallForm.key === deletedKey) {
        hgetallResult.value = {}
        hgetallResultEmpty.value = false
      }
    } else {
      ElMessage.warning(result.message || '字段不存在或删除失败')
    }
  } catch (error: any) {
    console.error('删除哈希字段失败:', error)
    ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message || '网络错误'))
  }
}

const resetHSetForm = () => {
  hsetForm.key = ''
  hsetForm.field = ''
  hsetForm.value = ''
}

const resetHGetForm = () => {
  hgetForm.key = ''
  hgetForm.field = ''
  hgetResult.value = null
}

const resetHGetAllForm = () => {
  hgetallForm.key = ''
  hgetallResult.value = {}
  hgetallResultEmpty.value = false
}

const copyHGetResult = () => {
  if (hgetResult.value) {
    navigator.clipboard.writeText(hgetResult.value)
    ElMessage.success('已复制到剪贴板')
  }
}

</script>

<style scoped>
.hash-operations {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 20px;
}

.hash-display {
  margin-top: 10px;
}

.hash-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
}

.hash-title {
  font-weight: 600;
  color: #409EFF;
  font-size: 14px;
}

.hash-actions {
  display: flex;
  gap: 8px;
}

.hash-content {
  max-height: 400px;
  overflow-y: auto;
}

.hash-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 8px;
  background-color: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  transition: all 0.2s;
}

.hash-item:hover {
  background-color: #f0f2f5;
  border-color: #409EFF;
}

.hash-field {
  flex-shrink: 0;
  margin-right: 12px;
}

.hash-separator {
  flex-shrink: 0;
  margin-right: 12px;
  font-weight: bold;
  color: #606266;
}

.hash-value {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-width: 0;
}

.value-text {
  flex: 1;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
  font-size: 13px;
  color: #2c3e50;
  word-break: break-all;
  margin-right: 8px;
}

.copy-btn {
  flex-shrink: 0;
  opacity: 0;
  transition: opacity 0.2s;
}

.hash-item:hover .copy-btn {
  opacity: 1;
}

.hash-content::-webkit-scrollbar {
  width: 6px;
}

.hash-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.hash-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.hash-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.operation-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.operation-card:hover {
  transform: translateY(-5px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.card-header .el-icon {
  margin-right: 5px;
}

.result-box {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #409EFF;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.result-header h4 {
  margin: 0;
  color: #409EFF;
  font-weight: 600;
}



pre {
  white-space: pre-wrap;
  word-break: break-all;
  margin: 0;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-family: 'Courier New', Courier, monospace;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .hash-operations {
    grid-template-columns: 1fr;
  }
}
</style>